<template>
  <a-spin :spinning="confirmLoading">
    <a-form :form="form" >
      <a-form-item label="业务ID" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
        <a-input v-if="modalOpera==1" v-decorator="['id', {rules: [{required: true}]}]" />
      </a-form-item>

      <p>
        分类扩展名称
        <a-icon type="right" />
      </p>
      <a-row :gutter="6">
        <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}" v-show="false">
          <a-form-item label="id" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator="['id', {rules: [{required: true, message: '请输入！'}]}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}">
          <a-form-item label="所在目录" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator="['filePathName', {rules: [{required: true, message: '请输入！'}]}]" disabled />
          </a-form-item>
        </a-col>

        <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}">
          <a-form-item label="片段别名" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator="['alias', {rules: [{required: true, min: 2, message: '请输入至少二个字符的规则！'}]}]" />
          </a-form-item>
        </a-col>

      </a-row>

      <a-row :gutter="6">
		<a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}">
		    <a-form-item label="片段编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
		      <a-input  v-decorator="['code', {rules: [{required: true, message: '请输入'}],initialValue:''}]"/>
		    </a-form-item>
		</a-col>
		  
        <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}">
          <a-form-item label="数据条数" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number style="width: 100%;" :min="0" v-decorator="['size', {rules: [{required: true, message: '请输入'}],initialValue:1}]"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider dashed />
      <p>
        内容系统字段
        <a-icon type="right" />
      </p>

      <a-row :gutter="6" v-for="(field,index) in fields" :key="index">
        <a-col :xl="{span: 5}" :lg="{span: 8}" :md="{span: 24}">
          <a-form-item :label="field.fieldNote" :labelCol="labelCol" :wrapperCol="{xs: {span: 24},sm:{ span: 4}}">
            <a-checkbox :value="field.fieldName" :checked="field.initCheck" v-if="!field.visibleCheck" @change="checkDefaultField"></a-checkbox>
          </a-form-item>
        </a-col>

        <a-col :xl="{span: 6}" :lg="{span: 6}" :md="{span: 24}">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
            <p>{{ field.fieldName }}( {{ field.fieldType }} )</p>
          </a-form-item>
        </a-col>

        <a-col :xl="{span: 5}" :lg="{span: 8}" :md="{span: 24}" v-if="field.visibleSwitch && checkDefaultFields.indexOf(field.fieldName)>=0">
          <a-form-item label="必填" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-switch v-model="field.initSwitch" />
          </a-form-item>
        </a-col>

        <a-col :xl="{span: 5}" :lg="{span: 8}" :md="{span: 24}" v-if="checkDefaultFields.indexOf(field.fieldName)>=0">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-model="field.reFieldNote" />
          </a-form-item>
        </a-col>

      </a-row>
      <a-divider dashed />
      <p>
        扩展字段
        <a-icon type="right" />
      </p>
      <div class="table-operator">
        <a-button style="margin-bottom: 5px;" type="primary" icon="plus" v-has="{perm:'role:save'}" @click="handleAddExtendsField">添加字段</a-button>
        <span style="font-size:12px"> PS:内容扩展字段(source,sourceUrl,text)不可用增加行</span>
      </div>
      <a-table
        bordered
        :pagination="false"
        ref="table"
        rowKey="id"
        :columns="columns"
        size="small"
        :dataSource="dataSource">
        <template v-for="col in extendsField" :slot="col.name" slot-scope="text, record, index">
          <a-form-item :key="col.name" style="padding:0;margin:0">
            <a-input-number
              v-if="col.type === 'number' "
              :min="0"
              v-decorator="[
                `${col.name}-${index}`,
                {rules: [{ required: col.required, message: '不能为空' }],
                 initialValue:text, validateTrigger: 'change'}
              ]"
              @change="e => handleChange(e, record.id, col.name, index,col.type)" />
            <a-input
              v-if="col.type === 'text' "
              :min="0"
              v-decorator="[
                `${col.name}-${index}`,
                {rules: [{ required: col.required, message: '不能为空' }],
                 initialValue:text, validateTrigger: 'change'}
              ]"
              @change="e => handleChange(e, record.id, col.name, index,col.type)" />

            <a-radio
              v-if="col.type === 'radio' "
              v-decorator="[
                `${col.name}-${index}`,
                {rules: [{ required: col.required, message: '不能为空' }],
                 initialValue:text, validateTrigger: 'change'}
              ]"
              @change="e => handleChange(e, record.id, col.name, index,col.type)">
            </a-radio>

            <a-checkbox
              v-if="col.type === 'checkbox' "
              :checked="text"
              v-decorator="[
                `${col.name}-${index}`,
                {rules: [{ required: col.required, message: '不能为空' }],
                 initialValue:text, validateTrigger: 'change'}
              ]"
              @change="e => handleChange(e, record.id, col.name, index,col.type)">
            </a-checkbox>

            <a-textarea
              v-if="col.type === 'textarea' "
              :rows="1"
              v-decorator="[
                `${col.name}-${index}`,
                {rules: [{ required: col.required, message: '不能为空' }],
                 initialValue:text, validateTrigger: 'change'}
              ]"
              @change="e => handleChange(e, record.id, col.name, index,col.type)">
            </a-textarea>

            <a-select
              v-if="col.type === 'select'"
              :options="inputType"
              v-decorator="[
                `${col.name}-${index}`,
                {rules: [{ required: true, message: '不能为空' }],
                 initialValue:text,validateTrigger: 'change'}
              ]"
              @change="e => handleChange(e, record.id, col.name, index,col.type)"></a-select>
          </a-form-item>
        </template>
        <span slot="action" slot-scope="text, record, index">
          <template>
            <a-popconfirm title="确定要删除该明细吗？" @confirm="handleDeleteExtendsField(record, index)" okText="确认" cancelText="取消">
              <a href="#">删除</a>
            </a-popconfirm>
          </template>
        </span>
      </a-table>

    </a-form>
  </a-spin>
</template>

<script>
import {
  getDesignById,
  updateFragmentDesignFile
} from '@/api/cms/webfile/fragment.js'
import pick from 'lodash.pick'
export default {
  data () {
    return {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 13
        }
      },
      modalTitle: '',
      modalOpera: 0, // 0：新增 1：编辑
      visible: false,
      confirmLoading: false,
      dataSource: [],
      inputType: [],
	  fields: [],
	  checkDefaultFields: [],
      form: this.$form.createForm(this),
      extendsField: [{
        name: 'code',
        type: 'text',
        required: true
      },
      {
        name: 'inputType',
        type: 'select',
        required: true
      }, {
        name: 'name',
        type: 'text',
        required: true
      },
      {
        name: 'isRequired',
        type: 'checkbox',
        required: true
      },
      {
        name: 'isSearch',
        type: 'checkbox',
        required: true
      },
      {
        name: 'defaultValue',
        type: 'text',
        required: true
      },
      {
        name: 'maxlength',
        type: 'number',
        required: true
      },
      {
        name: 'description',
        type: 'textarea',
        required: true
      },
      {
        name: 'sort',
        type: 'number',
        required: true
      }
      ],
      // 表头
      columns: [{
        title: '编码',
        dataIndex: 'code',
        align: 'center',
        width: '140px',
        scopedSlots: {
          customRender: 'code'
        }
      }, {
        title: '字段类型',
        dataIndex: 'inputType',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'inputType'
        }
      }, {
        title: '名称',
        dataIndex: 'name',
        align: 'center',
        width: '120px',
        scopedSlots: {
          customRender: 'name'
        }
      }, {
        title: '必填',
        dataIndex: 'isRequired',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'isRequired'
        }
      },
      {
        title: '可搜索',
        dataIndex: 'isSearch',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'isSearch'
        }
      }, {
        title: '默认值',
        dataIndex: 'defaultValue',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'defaultValue'
        }
      },
      {
        title: '最大长度',
        dataIndex: 'maxlength',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'maxlength'
        }
      },
      {
        title: '描述',
        dataIndex: 'description',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'description'
        }
      }, {
        title: '排序',
        dataIndex: 'sort',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'sort'
        }
      }, {
        title: '操作',
        dataIndex: 'action',
        align: 'center',
        width: '80px',
        scopedSlots: {
          customRender: 'action'
        }
      }
      ]
    }
  },
  created () {
	  this.selectInputType()
  },
  methods: {
    init (record) {
	  let that = this
      getDesignById({
        id: record.fileKey
      }).then(response => {
        const result = response.res
        let filePathName = '根目录'
        if (result.filePath) {
          filePathName = result.filePath
        }
        this.form.setFieldsValue({ 'filePathName': filePathName })
        this.form.setFieldsValue(pick(result, 'id', 'alias', 'size','code'))
        this.fields = result.modelFieldDtos
        if (result.extendFieldList) {
		    this.setDataSource(JSON.parse(result.extendFieldList))
        } else {
			  this.setDataSource([])
        }
        if (result.defaultFieldList) {
		  const defaultFieldList = JSON.parse(result.defaultFieldList)
		  if (defaultFieldList.length > 0) {
			  this.fields = defaultFieldList
			  defaultFieldList.forEach(function (item, index) {
				  if (item.initCheck) { that.checkDefaultFields.push(item.fieldName) }
			  })
		  }
        }
      })
    },
    initFields () {
      this.checkDefaultFields = []
      this.fields.forEach(function (item, index) {
        item.initCheck = false
        item.initSwitch = false
        item.reFieldNote = item.fieldNote
      })
    },
    checkDefaultField (e) { //  选中 系统内置的 checkbox
	  if (e.target.checked) {
	    this.checkDefaultFields.push(e.target.value)
	  } else {
	    const index = this.checkDefaultFields.indexOf(e.target.value)
	    if (index >= 0) {
	      this.checkDefaultFields.splice(index, 1)
	    }
	  }
	  this.getDefaultFieldByCode(e.target.value).initCheck = e.target.checked
    },
    getDefaultFieldByCode (code) {
	  let field = null
	  if (this.fields.length > 0) {
	    this.fields.forEach(function (item, index) {
	      if (item.fieldName === code) {
	        field = item
	      }
	    })
	    return field
	  }
    },

    handleSubmit () {
      const {
        form: {
          validateFields
        }
      } = this
      // this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
		  this.bulidData(values)
          updateFragmentDesignFile(values).then(response => {
			  this.$emit('ok')
			  if(response.code === 0){
				   this.$message.info(response.msg)
			  }else{
				   this.$message.error(response.msg)
			  }
          })
        }
        this.confirmLoading = false
      })
    },
    bulidData (values) {
      values.modelFieldDtos = this.fields
      values.extendFieldList = JSON.stringify(this.dataSource)
    },
    handleCancel () {
	  this.initFields()
      this.visible = false
      this.confirmLoading = false
    },
    handleAddExtendsField () {
      const newData = {
        code: '',
        inputType: this.inputType[0].value,
        name: '',
        isRequired: false,
        isSearch: false,
        defaultValue: '',
        maxlength: '',
        description: '',
        sort: 0,
        id: Date.now()
      }
      this.dataSource = [...this.dataSource, newData]
    },
    handleDeleteExtendsField (record, index) {
      this.dataSource.splice(index, 1)
    },
    setDataSource (data) {
      this.dataSource = data
    },
    clearDataSource () {
      this.dataSource = []
    },
    handleChange (e, key, column, index, inputType) {
      const newData = [...this.dataSource]
      const target = newData.filter(item => key === item.id)[0]
      if (target) {
        if (inputType === 'checkbox') {
			 target[column] = e.target.checked
        } else {
			 target[column] = (e instanceof Object) ? e.target.value : e
        }
      }
	  console.log(this.dataSource)
    },
    selectInputType () {
      const inputTypes = [{
        value: 'text',
        label: '输入框'
      }, {
        value: 'number',
        label: '数字'
      }, {
        value: 'date',
        label: '日期'
      }, {
        value: 'file',
        label: '文件'
      }, {
        value: 'picture',
        label: '图片'
      }]
      this.inputType = inputTypes
    }
  }
}
</script>
